<template>
  <div>
    <div ref="chartContainer" :style="{ width: width, height: height }" />
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import * as echarts from "echarts";
import { reactive } from "vue";
const chartContainer = ref(Math.random().toString(36).slice(2, 10));
// const echartsRef = ref < string > Math.random().toString(36).slice(2, 10);
let chartInstance = null;
const props = defineProps({
  width: {
    type: String,
    default: ""
  },
  height: {
    type: String,
    default: ""
  },
  option: {
    type: Object,
    required: true
  },
  activeCharts: {
    type: String,
    default: ""
  },
  chartnum: {
    type: Number,
    default: 12
  }
});
const legendDoms = ref(null);
onMounted(() => {
  initChart();
  window.addEventListener("resize", handelResize);
});
const handelResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
const emits = defineEmits(["getPieData"]);
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    const lendom = legendDoms.value;
    chartInstance.clear();
    chartInstance.setOption(props.option, true);
    chartInstance.on("click", params => {
      emits("getPieData", params.data);
    });
  }
};
watch(
  () => props.activeCharts,
  newOption => {
    console.log(newOption);
    handelResize();
  },
  { immediate: true }
);

watch(
  () => props.chartnum,
  newOption => {
    console.log(newOption);
    setTimeout(() => {
      chartInstance.resize();
    }, 100);
  }
);
watch(
  () => props.option,
  newOption => {
    console.log(newOption);
    if (chartInstance) {
      chartInstance = echarts.init(chartContainer.value);
      chartInstance.clear();
      chartInstance.setOption(newOption);
    }
  }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
  window.removeEventListener("resize", handelResize);
});
</script>

<style scoped lang="scss">
.legendDoms {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  height: 300px;
  background: white;
}
</style>
